package com.mti.zhpt.service.impl;


import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageInfo;
import com.mti.zhpt.base.BasePageHelper;
import com.mti.zhpt.base.BaseServiceImpl;
import com.mti.zhpt.dao.SystemUserMapper;
import com.mti.zhpt.model.SystemUser;
import com.mti.zhpt.shared.utils.MD5Util;
import com.mti.zhpt.utils.BusinessException;

import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author 潘文俊
 * @since 2018-09-03
 */
@Slf4j
@Service
@Transactional
public class SystemUserServiceImpl extends BaseServiceImpl<SystemUser> {
	
	@Autowired
	private SystemUserMapper systemUserMapper;
	
	public SystemUser loginUser(SystemUser user) {
		Boolean flg = false;
		SystemUser result = new SystemUser();
		result.setUsername(user.getUsername());
		result = systemUserMapper.selectOne(result);
		if (result != null && result.getPassword() != null) {
			flg = MD5Util.authenticatePassword(result.getPassword(), user.getPassword());
		}
		if (result == null || !flg) {
			throw new BusinessException(BusinessException.CODE_INCORRECT_USER, "用户名或密码错误");
		}
		
		return result;
	}

	public SystemUser saveUser(SystemUser user) {
		SystemUser entity = new SystemUser();
		entity.setUsername(user.getUsername());
		entity = systemUserMapper.selectOne(entity);
		if (entity != null) {
			throw new BusinessException(BusinessException.CODE_INSERT_ERROR, "用户名不可重复");
		}
		user.setCreateTime(new Date());
		this.save(user);
		return user;
	}

	public SystemUser updateUser(SystemUser user) {
		user.setUsername(null);
		this.update(user);
		return user;
	}

	public PageInfo<SystemUser> queryUserList(BasePageHelper<SystemUser> pageHelper) {
		pageHelper.setSort("su.createTime");
		return new PageInfo<SystemUser>(systemUserMapper.pageUserList(pageHelper));
	}

	public List<SystemUser> findUserList(SystemUser user) {
		return systemUserMapper.select(user);
	}

}
